package com.privatework.backedserver.controller.ai;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.FaceVerifyRequest;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.privatework.common.entity.chooseclass.ChooseClassInfo;
import com.privatework.common.entity.classinfo.ClassInfo;
import com.privatework.common.entity.user.UserEntity;
import com.privatework.common.repository.chooseclass.ChooseClassInfoRepository;
import com.privatework.common.repository.classinfo.ClassInfoRepository;
import com.privatework.common.repository.user.UserRepository;
import com.privatework.common.requestvo.AiLoginReqVo;
import com.privatework.common.requestvo.system.UserReqVo;
import com.privatework.common.service.system.UserService;
import com.privatework.common.utils.IDUtils;
import com.privatework.common.utils.ResultVoUtil;
import com.privatework.common.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author johnny
 * @create 2021-04-14 9:31 上午
 **/

@RestController
@Slf4j
@RequestMapping("/ai")
public class AiController {

    public static void main(String[] args) {

        Object jsonObject = (JsonObject) JSONObject.stringToValue("{\n" +
                "  \"result\": {\n" +
                "    \"face_token\": \"50b2070472df4e951e0d923675e0f7d3\",\n" +
                "    \"user_list\": [{\n" +
                "      \"score\": 94.320640563965,\n" +
                "      \"group_id\": \"student\",\n" +
                "      \"user_id\": \"3044ebba72c541a7998a80450480837f\",\n" +
                "      \"user_info\": \"{\\\"phone\\\":\\\"17625013741\\\",\\\"username\\\":\\\"johnny\\\"}\"\n" +
                "    }]\n" +
                "  },\n" +
                "  \"log_id\": 12011019989,\n" +
                "  \"error_msg\": \"SUCCESS\",\n" +
                "  \"cached\": 0,\n" +
                "  \"error_code\": 0,\n" +
                "  \"timestamp\": 1618371259\n" +
                "}");

        System.out.println(jsonObject.toString());
    }

    private final AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

    {
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private ClassInfoRepository classInfoRepository;
    @Autowired
    private ChooseClassInfoRepository chooseClassInfoRepository;
    //设置APPID/AK/SK
    public static final String APP_ID = "23985909";
    public static final String API_KEY = "dTK3nrc6DGI304EDPpyXEcSu";
    public static final String SECRET_KEY = "ZfRo3HhG7SzoESVA4lCFyn1yeeGsIcT2";

    @GetMapping("/delete")
    public void delete() {

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        String groupId = "student";
        // 删除用户组
        JSONObject res = client.groupDelete(groupId, options);
        try {
            System.out.println(res.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/dafen")
    public void dafen() {

        String url = "https://cdn.askajohnny.com/image-20210414095813895.png";

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age,beauty");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");
        options.put("liveness_control", "LOW");

        String image = "https://cdn.askajohnny.com/image-20210414132411532.png";
        //String image = "https://cdn.askajohnny.com/image-20210414225834646.png";
        //String image = "https://cdn.askajohnny.com/image-20210414230113135.png";
        String imageType = "URL";

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        try {
            System.out.println(res.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @PostMapping("/checkAiLogin")
    public ResultVo checkAiLogin(@RequestBody UserReqVo userReqVo) {
        if (StringUtils.isNotEmpty(userReqVo.getUsername())) {
            UserEntity byUsername = userRepository.findByUsername(userReqVo.getUsername());
            if (byUsername != null) {
                ResultVo resultVO = new ResultVo();
                resultVO.setData(null);
                resultVO.setCode(200);
                resultVO.setMsg("exist");
                return resultVO;
            }
        }
        return ResultVoUtil.success();
    }

    @PostMapping("/aiLogin")
    public ResultVo aiLogin(@RequestBody AiLoginReqVo aiLoginReqVo) {

        UserEntity userEntity = null;

        HashMap<String, String> options = new HashMap<>();
        options.put("max_face_num", "3");
        options.put("match_threshold", "70");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "3");

        String image = aiLoginReqVo.getBase64ImageStr();
        String imageType = "BASE64";
        //String imageType = "URL";
        String groupIdList = "student,teacher";

        // 人脸搜索
        JSONObject res = client.search(image, imageType, groupIdList, options);
        try {
            System.out.println(res.toString(2));

            String error_mgs = res.getString("error_msg");
            if (error_mgs.equals("SUCCESS")) {
                JSONObject result = res.getJSONObject("result");

                JSONArray user_list = result.getJSONArray("user_list");
                if (user_list != null) {
                    if (!user_list.isNull(0)) {
                        JSONObject user_listJSONObject = user_list.getJSONObject(0);

                        double score = user_listJSONObject.getDouble("score");
                        String group_id = user_listJSONObject.getString("group_id");
                        String uuid_user_id = user_listJSONObject.getString("user_id");
                        log.info("【score： {}】", score);
                        log.info("【group_id： {}】", group_id);
                        log.info("【uuid_user_id： {}】", uuid_user_id);

                        userEntity = userRepository.findByAiUid(uuid_user_id);
                    }
                }
            } else {
                int error_code = res.getInt("error_code");
                if (error_code == 222207) {
                    log.info("【不存在该用户 走注册逻辑】");

                    return ResultVoUtil.regist();
                }

                log.warn("【识别有误】");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        log.info("【aiLoginReqVo ： {}】", aiLoginReqVo);
//        String image = aiLoginReqVo.getBase64ImageStr();
//        FaceVerifyRequest req = new FaceVerifyRequest(image, "BASE64");
//        ArrayList<FaceVerifyRequest> list = new ArrayList<FaceVerifyRequest>();
//        list.add(req);
//        JSONObject res = client.faceverify(list);
//        try {
//            System.out.println(res.toString(2));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        if (userEntity != null) {
            log.info("【match success】");
        } else {
            log.info("【match fail】");
        }
        return ResultVoUtil.success(userEntity);
    }

    @PostMapping("/aiRegist")
    public ResultVo aiRegist(@RequestBody UserReqVo userReqVo) {

        String username = userReqVo.getUsername();
        UserEntity byUsername = userRepository.findByUsername(username);
        if (byUsername == null) {
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername(username);
            userEntity.setPassword(userReqVo.getPassword());
            userEntity.setEnable(true);
            userEntity.setRealname(userReqVo.getRealname());
            userEntity.setGender(userReqVo.getGender());
            userEntity.setHeadImage("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            String userId = IDUtils.makeId();
            userEntity.setAiUid(userId);
            userEntity.setRole("student");

            userRepository.save(userEntity);
            List<Long> roleIds = new ArrayList<>();
            roleIds.add(2L);
            userService.handleUserRole(roleIds, userEntity.getId());


//            List<ClassInfo> all = classInfoRepository.findAll();
//            all.forEach(classInfo -> {
//                ChooseClassInfo chooseClassInfo = new ChooseClassInfo();
//                chooseClassInfo.setUserId(userEntity.getId());
//                chooseClassInfo.setClassInfoId(classInfo.getId());
//                chooseClassInfoRepository.save(chooseClassInfo);
//            });

            //传入可选参数调用接口
            HashMap<String, String> options = new HashMap<>();

            Gson gson = new Gson();

            Map<String, String> userInfo = new HashMap<>();
            userInfo.put("username", userEntity.getUsername());
            userInfo.put("realname", userEntity.getRealname());
            String userStr = gson.toJson(userInfo);

            options.put("user_info", userStr);
            options.put("quality_control", "NORMAL");
            options.put("liveness_control", "LOW");
            options.put("action_type", "REPLACE");

            String image = userReqVo.getImgBase64();
//            String imageType = "BASE64";
            //String image = "https://cdn.askajohnny.com/image-20210414132411532.png";
            String imageType = "BASE64";
            //String imageType = "URL";
            String groupId = "student";


            // 人脸注册
            JSONObject res = client.addUser(image, imageType, groupId, userId, options);
            try {
                System.out.println(res.toString(2));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return ResultVoUtil.success();
        } else {
            log.info("【username 已经存在】");
        }
        return null;


        // 传入可选参数调用接口
//        HashMap<String, String> options = new HashMap<>();
//
//        UserEntity userEntity = userRepository.findById(1L).orElse(null);
//
//        Gson gson = new Gson();
//
//        Map<String, String> userInfo = new HashMap<>();
//        userInfo.put("username", userEntity.getUsername());
//        userInfo.put("phone", userEntity.getPhone());
//        String userStr = gson.toJson(userInfo);
//
//        options.put("user_info", userStr);
//        options.put("quality_control", "NORMAL");
//        options.put("liveness_control", "LOW");
//        options.put("action_type", "REPLACE");
//
//        String image = "https://cdn.askajohnny.com/image-20210414095813895.png";
//        String imageType = "URL";
//        String groupId = "student";
//        String userId = "3044ebba72c541a7998a80450480837f";
//
//        // 人脸注册
//        JSONObject res = client.addUser(image, imageType, groupId, userId, options);
//        try {
//            System.out.println(res.toString(2));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
    }
}